package work.comeback.omo.model.user;

import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;

public class UserBeanTypeAdapter extends TypeAdapter<UserBean> {
    @Override
    public void write(JsonWriter out, UserBean user) throws IOException {
        out.beginObject();
        out.name("id").value(user.getId());
        out.name("username").value(user.getUsername());
        out.name("role").value(user.getRole());
        out.name("avatarUrl").value(user.getAvatarUrl());
        out.endObject();
    }

    @Override
    public UserBean read(JsonReader in) throws IOException {
        UserBean user = new UserBean();
        in.beginObject();
        while (in.hasNext()) {
            switch (in.nextName()) {
                case "id":
                    user.setId(in.nextInt());
                case "username":
                    user.setUsername(in.nextString());
                    break;
                case "role":
                    user.setRole(in.nextString());
                    break;
                case "avatarUrl":
                    user.setAvatarUrl(in.nextString());
                    break;
                default:
                    in.skipValue();
                    break;
            }
        }
        in.endObject();
        return user;
    }
}